package com.ptszyxx.popose.module.main.trip;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ptszyxx.popose.common.utils.YVipUtil;
import com.ptszyxx.popose.databinding.FragmentTripBinding;
import com.ptszyxx.popose.module.main.trip.adapter.TripAdapter;
import com.ptszyxx.popose.module.main.trip.vm.TripVM;
import com.ysg.base.BaseFragment;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.trip.TripEntity;

import java.util.List;

public class TripFragment extends BaseFragment<FragmentTripBinding, TripVM> {
    private TripAdapter adapter;
    private boolean statusBarFlag = true;

    public TripFragment(){
    }

    public TripFragment(boolean statusBarFlag){
        this.statusBarFlag = statusBarFlag;
    }

    @Override
    public int initContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return R.layout.fragment_trip;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public TripVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getActivity().getApplication());
        return ViewModelProviders.of(this, factory).get(TripVM.class);
    }

    @Override
    public void initStatusBar() {
        if (statusBarFlag){
            super.initStatusBar();
        }
    }

    @Override
    public void initAdapter() {
        super.initAdapter();
        adapter = new TripAdapter(viewModel);
        binding.refreshView.initAdapterNoLine(adapter);
    }

    @Override
    public void initData() {
        super.initData();
        viewModel.requestList(true);
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onRefreshEvent.observe(this, new Observer<List<TripEntity>>() {
            @Override
            public void onChanged(List<TripEntity> list) {
                setAdapterUI(list);
            }
        });
        viewModel.uc.onDetailEvent.observe(this, o -> onJumpDetail((TripEntity)o));
    }

    private void setAdapterUI(List<TripEntity> list) {
        binding.refreshView.setAdapterUI(adapter, list, viewModel.isRefresh());
    }

    private void onJumpDetail(TripEntity entity) {
        if (YVipUtil.isVip(getContext(), true)){
            YActivityUtil.getInstance().jumpTripDetail(viewModel, entity);
        }
    }

}
